﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.IO;
using System.Drawing;
using Slja.Model;

namespace Slja.WEB.Finance
{
    public partial class DailyAccount : System.Web.UI.Page
    {
        DataTable _dtTableColumns;
        public DataTable DtTableColumns
        {
            get {
                if (_dtTableColumns == null)
                {
                    _dtTableColumns = new BLL.ImportData().GetTableColumns("");
                }
                return _dtTableColumns;
            }
        }
        List<TableCol> _tableColModel;
        public List<TableCol> TableColModel
        {
            get
            {
                if (_tableColModel == null)
                {
                    _tableColModel = new BLL.ImportData().GetComparableTableColumnsModel("");
                }
                return _tableColModel;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            btnGenerate.Click += new EventHandler(btnGenerate_Click);
            btnOutput.Click += new EventHandler(btnOutput_Click);
            GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
            GridView1.AutoGenerateColumns = true;
            if (!IsPostBack)
            {
                BindMonth();
            }
        }

        void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {                
                DataRowView drv = (DataRowView)e.Row.DataItem;
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    ChangeCellBgColor(DtTableColumns, drv.DataView.Table.Columns[i].ColumnName, e.Row.Cells[i],drv[i]);
                }
            }
        }

        private void ChangeCellBgColor(DataTable dt,string ColName,TableCell cell,object colVal)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["columnname"].ToString() + dt.Rows[i]["rank"].ToString() == ColName)
                {
                    switch (dt.Rows[i]["tablename"].ToString())
                    {
                        case "f_Receivable":
                            cell.BackColor = Color.LightSkyBlue;break;
                        case "f_Payable":
                            cell.BackColor = Color.LightPink;break;
                        case "f_Checking":
                             cell.BackColor = Color.LightGreen;break;
                    }
                    if(IsChangeColorForAimDate(dt.Rows[i]["tablename"].ToString()
                        ,dt.Rows[i]["columnname"].ToString()
                        ,colVal))
                    {
                        cell.ForeColor = Color.Red;

                        cell.Font.Italic = true;
                    }
                }
            }
        }
        private bool IsChangeColorForAimDate(string tablename, string col,object colVal)
        {
            bool IsAimCol = TableColModel.Exists(delegate(TableCol tc)
            {
                return !string.IsNullOrEmpty(tc.ColumnName)&& 
                    tc.TableName == tablename 
                    && col.IndexOf(tc.ColumnName) > -1;
            });
            if (IsAimCol)
            {
                DateTime? dtm = null;
                if (colVal != DBNull.Value && colVal.ToString().Trim()!=""
                       && colVal.ToString().Trim()!="0"
                    ) { dtm = DateTime.Parse(colVal.ToString()); }


                return dtm.HasValue
                    && dtm.Value.Year.ToString() == drpYear.SelectedValue
                    && dtm.Value.Month.ToString() == drpMonth.SelectedValue;
            }
            else
            {
                return false;
            }
        }
        void btnOutput_Click(object sender, EventArgs e)
        {
            DataTable dt = GetDataSource();
            GridView1.DataSource = dt;
            GridView1.DataBind();
            //GridView1.Visible = false;
            btnOutput.Visible = true;
            Export("筛选结果.xls");
        }
        DataTable GetDataSource()
        {
            DataTable dt = null;
            if (rdbDayQuery.Checked)
            {
                DateTime dt1 = DateTime.Parse(tbxStart.Text);
                DateTime dt2 = DateTime.Parse(tbxEnd.Text);
                dt = new BLL.ImportData().GetJoinedData(dt1, dt2);
            }
            else if (rdbMonthQuery.Checked)
            {
                int Year = int.Parse(drpYear.SelectedValue);
                int Month = int.Parse(drpMonth.SelectedValue);
                DateTime dt1 = new DateTime(Year, Month, 1);
                dt = new BLL.ImportData().GetJoinedData(dt1);
            }
            return dt;
        }
        void btnGenerate_Click(object sender, EventArgs e)
        {

            GridView1.DataSource = GetDataSource();
            GridView1.DataBind();
            //GridView1.Visible = false;
            btnOutput.Visible = true; 
           // Export("筛选结果.xls");
            
        }
        private void BindMonth()
        {
            for (int i = 1; i <= 12; i++)
            {
                drpMonth.Items.Add(new ListItem(i.ToString() + "月", i.ToString()));
            }
            
        }
        protected int Year
        {
            get { return int.Parse(drpYear.SelectedValue); }
        }
        protected int Month
        {
            get { return int.Parse(drpMonth.SelectedValue); }
        }      
        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="FileType"></param>
        /// <param name="FileName"></param>
        private void Export(string FileName)
        {
       

            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
            Response.ContentType = "application/ms-excel";
            this.EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            GridView1.RenderControl(hw);
            Response.Write(tw.ToString());
            Response.End();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            // Confirms that an HtmlForm control is rendered for
        }

    }
}